package io.renren.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.renren.dao.CustomSettlementDao;
import io.renren.dao.PersonDispatchDao;
import io.renren.dao.SalaryBasicinfoDao;
import io.renren.dao.VGeneralEmpInfoDao;
import io.renren.entity.CustomSettlementEntity;
import io.renren.entity.SalaryBasicinfoEntity;
import io.renren.entity.VEmpInfoEntity;
import io.renren.service.BaseService;
import io.renren.service.EmpSyncToB1Service;
import io.renren.utils.*;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


/**
 * 员工数据同步B1
 * Created by wdj on 2017/8/1.
 */
@Service("empSyncToB1Service")
public class EmpSyncToB1ServiceImpl extends BaseService implements EmpSyncToB1Service {

    @Autowired
    private VGeneralEmpInfoDao vGeneralEmpInfoDao;

    @Autowired
    PersonDispatchDao personDispatchDao;

    @Autowired
    private CustomSettlementDao customSettlementDao;

    @Autowired
    private SalaryBasicinfoDao salaryBasicinfoDao;

    /**
     * 批量添加员工
     * @throws Exception
     */
    @Override
    @Transactional
    public void empSynToB1() throws Exception {
        Map<String, Object> params = new HashedMap();
        List<VEmpInfoEntity> vEmpInfoList = vGeneralEmpInfoDao.queryUnploadList(params);

        Map<String, Object> queryParams = new HashedMap();

//        List<String> dataList = new ArrayList();
          JSONArray dataList = new JSONArray();

        for (VEmpInfoEntity vemp:vEmpInfoList) {
//            Map<String, Object> emp_data = new HashedMap();
            JSONObject emp_data = new JSONObject();
            emp_data.put("lastName",vemp.getId());                  //员工编号
            emp_data.put("firstName",vemp.getName());               //员工姓名
            emp_data.put("sex",vemp.getSex());                      //性别        M:男  F:女
            emp_data.put("birthDate", DateUtils.format(vemp.getBirthday()));           //员工出生年月
            emp_data.put("passportNo", vemp.getIdno());             //员工身份证号
            emp_data.put("startDate",DateUtils.format(vemp.getJoinDate()));           //员工入职时间
            emp_data.put("termDate","2020-8-8");                    //离职日期
            emp_data.put("status",vemp.getIswork());                //员工状态  0:空值 1:在职 2:离职 3:待岗
            emp_data.put("u_gwbh",vemp.getPost());                  //员工岗位编号
            emp_data.put("u_xz","2");                               //员工类别  0:空值 1:管理员工  2:劳务员工

            dataList.add(emp_data);
        }

        if (dataList != null &&  dataList.size() > 0) {
            String key = Global.getConfig("b1key");// 获取key
            String url = Global.getConfig("b1url9");// 获取url
//            JSONArray.;
            String testString = "[{\"sex\":\"0\",\"startDate\":1501603200000,\"termDate\":\"\"," +
                    "\"u_xz\":\"0\",\"u_gwbh\":\"5\",\"status\":\"0\",\"birthDate\":1502035200000," +
                    "\"firstName\":\"luna\",\"passportNo\":\"AEQ\",\"lastName\":25}]";

            queryParams.put("data",dataList.toJSONString());
            String sign = Sha1Util.SHA1(queryParams, key);// 计算签名
            queryParams.put("sign",sign);

            logger.info("data:" + dataList.toJSONString());
            logger.info("url:" + url);
            logger.info("sign:" + sign);
            // 发送请求
            String result = HttpClientUtils.doPost(url, queryParams);
            logger.info("请求的结果:"+result);
            if (result != null) {
                result = result.replace("null", "''");
                Map<String, Object> b1Map = FastJsonUtils.stringToCollect(result);
                if (b1Map != null && b1Map.size() > 0) {
                    if (b1Map.get("isSuc") != null && (b1Map.get("isSuc").equals("y"))) {
                        //将派遣表数据改成已同步
                        for (VEmpInfoEntity vemp2:vEmpInfoList) {
                            vemp2.setIsupload("1");
                        }
                        //批量更改已同步状态
                        vGeneralEmpInfoDao.updateStatusBatch(vEmpInfoList);
                        logger.info("员工数据添加B1成功!");
                    }
                }
            }
        } else {
            logger.info("没有需要添加的数据");
        }


    }

    /**
     * 从B1查询员工接口
     */
    @Override
    @Transactional
    public void queryEmpFromB1() throws Exception {
        Map<String, Object> queryParams = new HashedMap();
        String key = Global.getConfig("b1key");// 获取key
        String url = Global.getConfig("b1url19");// 获取url

        String sign = Sha1Util.SHA1(queryParams, key);// 计算签名
        queryParams.put("sign",sign);

        // 发送请求
        String result = HttpClientUtils.doPost(url, queryParams);
        logger.info("请求的结果:"+result);
        if (result != null) {
            result = result.replace("null", "''");
            Map<String, Object> b1Map = FastJsonUtils.stringToCollect(result);
            if (b1Map != null && b1Map.size() > 0) {
                if (b1Map.get("isSuc") != null && (b1Map.get("isSuc").equals("y"))) {
                    System.out.println(b1Map.get("data"));


                }

            }

        }

    }

    /**
     * B1编辑员工接口:其中empId 、u_xz必须有值
     */
    @Transactional
    public void editEmpSynToB1(Map<String, Object> params) throws Exception {
        if (params != null && params.get("empId") != null) {
            String data = FastJsonUtils.collectToString(params);
            String key = Global.getConfig("b1key");// 获取key
            String url = Global.getConfig("b1url4");// 获取 编辑员工接口 url

            Map<String, Object> requestParams = new HashedMap();
            requestParams.put("data", data);
            String sign = Sha1Util.SHA1(requestParams, key);// 计算签名
            requestParams.put("sign", sign);

            logger.info("data:" + data);
            logger.info("url:" + url);
            logger.info("sign:" + sign);
            String result = HttpClientUtils.doPost(url, params);// 发送请求
            logger.info("请求的结果:" + result);

            if (result != null) {
                result = result.replace("null", "''");
                Map<String, Object> b1Map = FastJsonUtils.stringToCollect(result);
                if (b1Map != null && b1Map.size() > 0) {
                    if (b1Map.get("isSuc") != null && (b1Map.get("isSuc").equals("y"))) {
                        //编辑员工成功之后的处理

                    }
                }
            } else {
                logger.info("没有需要添加的数据");
            }

        }


    }

    /**
     * 员工结算 同步B1接口
     * @throws Exception
     */
    @Override
    @Transactional
    public void addEmployeeSettleSyncToB1() throws Exception {
        //拼接参数
        Map<String, Object> queryParams = new HashMap<>();
        List<String> data = new ArrayList(); //请求中data参数集合

        //1.查出所有的结算点
        List<CustomSettlementEntity> customSettlementEntities = customSettlementDao.getSettlementList();

        for (CustomSettlementEntity customSettlementEntity:customSettlementEntities) {

            //查询出该结算点下待同步的员工工资表数据集合，以后可以带分年分月
            Map<String,Object> params = new HashMap<>();
            params.put("settlementid",customSettlementEntity.getId());
            List<SalaryBasicinfoEntity> salaryBasicinfoEntitites = salaryBasicinfoDao.getListByMap(params);

            Map<String, Object> dataUnit = new HashedMap();
            List<String> item = new ArrayList(); //明细集合
            dataUnit.put("deaID",customSettlementEntity.getContractNo());       //合同编号
            dataUnit.put("User",customSettlementEntity.getDutyPerson());        //责任人
            dataUnit.put("Status","1");      //单据状态
            String DocNum = "A" + DateUtils.format(new Date(),"yyyyMMddHHmmss");
            dataUnit.put("DocNum",DocNum);      //单据编号
            dataUnit.put("Dept",customSettlementEntity.getDutyDepartment());        //责任部门

            for (SalaryBasicinfoEntity salaryBasicinfoEntity: salaryBasicinfoEntitites) {
                Map<String, Object> itemSingle = new HashedMap();
                itemSingle.put("pawardpen",salaryBasicinfoEntity.getQtkkLwygProjectfk());                     //项目奖罚款
                itemSingle.put("unemployment",salaryBasicinfoEntity.getSbbcShiy());                  //失业
                itemSingle.put("outamount","");                     //未清金额
                itemSingle.put("dispatchcheck",salaryBasicinfoEntity.getQtkkLwygPaiqkh());                 //派遣考核款
                itemSingle.put("reservethree","");                  //预留
                itemSingle.put("situationexplain",salaryBasicinfoEntity.getSfgzRemark());              //情况说明
                itemSingle.put("remark1","");                       //备用
                itemSingle.put("counterfee",salaryBasicinfoEntity.getSfgzShouxf());                    //手续费
                itemSingle.put("cDepartment","");                   //员工部门
                itemSingle.put("grosspay",salaryBasicinfoEntity.getYfgzSalary());                      //应发工资
                itemSingle.put("remark2","");                       //备用
                itemSingle.put("manaunion",salaryBasicinfoEntity.getQtkkGlygGonghui());                     //管理员工工会
                itemSingle.put("setname",customSettlementEntity.getUnitName());                       //结算单位名称
                itemSingle.put("settlementunitID",customSettlementEntity.getUnitName());              //结算单位编号
                itemSingle.put("econcompen",salaryBasicinfoEntity.getSfgzJinjbcj());                    //经济补偿金
                itemSingle.put("jobinjury",salaryBasicinfoEntity.getSbgrGongs());                     //工伤
                itemSingle.put("year",salaryBasicinfoEntity.getYear());                          //年
                itemSingle.put("IDnumber",salaryBasicinfoEntity.getCardno());                      //身份证号
                itemSingle.put("socisecuassis",salaryBasicinfoEntity.getYfgzShebaobz());                 //社保补助
                itemSingle.put("employeesID",salaryBasicinfoEntity.getEmpid());                   //员工编号
                itemSingle.put("reservefive","");                   //预留
                itemSingle.put("coverall",salaryBasicinfoEntity.getQtkkGlygWorkclothes());                      //工作服
                itemSingle.put("welfare",salaryBasicinfoEntity.getQtkkLwygFulif());                       //福利费
                itemSingle.put("filltax",salaryBasicinfoEntity.getQtkkLwygBupersontax());                       //补个税
                itemSingle.put("embankID","");                      //员工银行卡号
                itemSingle.put("reserveone","");                    //预留
                itemSingle.put("laborsupplies",salaryBasicinfoEntity.getQtkkLwygLaobaoyp());                 //劳保用品
                itemSingle.put("LineTotal","");                     //实收总额
                itemSingle.put("tax",salaryBasicinfoEntity.getBasicTax());                           //税额
                itemSingle.put("month",salaryBasicinfoEntity.getYear());                         //月
                itemSingle.put("pension",salaryBasicinfoEntity.getSbgrYangl());                       //养老
                itemSingle.put("reservetwo","");                    //预留
                itemSingle.put("manafund",salaryBasicinfoEntity.getQtkkLwygManagementpay());                      //管理费用
                itemSingle.put("state",salaryBasicinfoEntity.getStatus());                         //状态
                itemSingle.put("medicalcare",salaryBasicinfoEntity.getSbgrYil());                   //医疗
                itemSingle.put("realwage",salaryBasicinfoEntity.getSfgzSalary());                      //实发工资
                itemSingle.put("employeeName",salaryBasicinfoEntity.getEmpname());                  //员工姓名
                itemSingle.put("oExplain",salaryBasicinfoEntity.getSfgzRemark());                      //情况说明
                itemSingle.put("manaperson",salaryBasicinfoEntity.getQtkkGlygGerenwl());                    //管理员工个人往来
                itemSingle.put("protocolID","");                    //协议编号
                itemSingle.put("labourunion",salaryBasicinfoEntity.getQtkkLwygGonghui());                   //劳务个人工会
                itemSingle.put("taxdeduction",salaryBasicinfoEntity.getSfgzTax());                  //扣税
                itemSingle.put("physicalexamfee",salaryBasicinfoEntity.getQtkkGlygTijian());               //体检费
                itemSingle.put("prizefine",salaryBasicinfoEntity.getQtkkLwygProjectfk());                     //奖罚款
                itemSingle.put("wefee",salaryBasicinfoEntity.getQtkkLwygShuidf());                         //水电费
                itemSingle.put("accumfund",salaryBasicinfoEntity.getSbgrGongjjZc());                     //公积金
                itemSingle.put("overpay",salaryBasicinfoEntity.getYfgzOuttimepay());                       //加班费
                itemSingle.put("seriousillness",salaryBasicinfoEntity.getSbgrDab());                //大病
                itemSingle.put("ueeassis",salaryBasicinfoEntity.getQtkkLwygGonghyilhz());                      //工会医疗互助
                itemSingle.put("boardfunds",salaryBasicinfoEntity.getQtkkGlygFood());                    //伙食费
                itemSingle.put("laborperson",salaryBasicinfoEntity.getQtkkLwygGerenwl());                   //劳务员工个人往来
                itemSingle.put("laborstaffmeals",salaryBasicinfoEntity.getQtkkLwygFood());               //劳务元工伙食费
                itemSingle.put("manapefee","");                     //体检费（待修改）
                itemSingle.put("ludepartment","");                  //用工单位部门
                itemSingle.put("reservefour","");                   //预留
                item.add(FastJsonUtils.collectToString(itemSingle));
            }
            dataUnit.put("item",item);
            dataUnit.put("ServType","");                            //单据类型
            dataUnit.put("DocDate",DateUtils.format(new Date()));                             //单据日期
            data.add(FastJsonUtils.collectToString(dataUnit));
        }

        String key = Global.getConfig("b1key");// 获取key
        String url = Global.getConfig("b1url15");// 获取url
        queryParams.put("data", data.toString());
        String sign = Sha1Util.SHA1(queryParams, key);// 计算签名
        queryParams.put("sign", sign);

        logger.info("data:" + data.toString());
        logger.info("url:" + url);
        logger.info("sign:" + sign);
        String result = HttpClientUtils.doPost(url, queryParams);// 发送请求
        if (result != null) {
            result = result.replace("null", "''");
            Map<String, Object> b1Map = FastJsonUtils.stringToCollect(result);
            if (b1Map != null && b1Map.size() > 0) {
                if (b1Map.get("isSuc") != null && (b1Map.get("isSuc").equals("y"))) {
                    //接口成功掉用后处理

                }
            }

        }

    }

    /**
     * 员工工资支付 同步B1接口
     * @throws Exception
     */
    @Override
    @Transactional
    public void employeeSettleSuccSyncToB1() throws Exception {
        Map<String, Object> queryParams = new HashMap<>();
        List<String> data = new ArrayList(); //请求中data参数集合

        String docNum = "";         //结算单号
        String failAmt = "";        //导出失败金额
        String sucAmt = "";         //导出成功金额
        String payAccount = "";     //付款账户

        //拼接参数
        String key = Global.getConfig("b1key");// 获取key
        String url = Global.getConfig("b1url16");// 获取url
        queryParams.put("docNum", "");
        queryParams.put("failAmt", "");
        queryParams.put("sucAmt", "");
        queryParams.put("payAccount", "");
        String sign = Sha1Util.SHA1(queryParams, key);// 计算签名
        queryParams.put("sign", sign);

        logger.info("data:" + "");
        logger.info("url:" + url);
        logger.info("sign:" + sign);
        String result = HttpClientUtils.doPost(url, queryParams);// 发送请求
        if (result != null) {
            result = result.replace("null", "''");
            Map<String, Object> b1Map = FastJsonUtils.stringToCollect(result);
            if (b1Map != null && b1Map.size() > 0) {
                if (b1Map.get("isSuc") != null && (b1Map.get("isSuc").equals("y"))) {
                    //接口成功掉用后处理

                }
            }

        }


    }

    /**
     * 维护付款失败信息 同步B1接口
     * @throws Exception
     */
    @Override
    @Transactional
    public void employeeSettleFailSyncToB1() throws Exception {
        Map<String, Object> queryParams = new HashMap<>();
        List<String> data = new ArrayList(); //请求中data参数集合

        String docNum = "";          //结算单号
        String failAmt = "";         //付款失败金额
        String payAccount = "";      //付款账户

        //拼接参数
        String key = Global.getConfig("b1key");// 获取key
        String url = Global.getConfig("b1url17");// 获取url
        queryParams.put("docNum", "");
        queryParams.put("failAmt", "");
        queryParams.put("payAccount", "");
        String sign = Sha1Util.SHA1(queryParams, key);// 计算签名
        queryParams.put("sign", sign);

        logger.info("data:" + "");
        logger.info("url:" + url);
        logger.info("sign:" + sign);
        String result = HttpClientUtils.doPost(url, queryParams);// 发送请求
        if (result != null) {
            result = result.replace("null", "''");
            Map<String, Object> b1Map = FastJsonUtils.stringToCollect(result);
            if (b1Map != null && b1Map.size() > 0) {
                if (b1Map.get("isSuc") != null && (b1Map.get("isSuc").equals("y"))) {
                    //接口成功掉用后处理

                }
            }

        }





    }

    /**
     * 员工余额查询
     * @throws Exception
     */
    @Override
    @Transactional
    public void getEmployeeBalanceSyncToB1() throws Exception {
        //拼接参数
        Map<String, Object> queryParams = new HashMap<>();
        List<String> data = new ArrayList(); //请求中data参数集合

        String empId = ""; //员工ID

        String key = Global.getConfig("b1key");// 获取key
        String url = Global.getConfig("b1url18");// 获取url
        queryParams.put("empId", empId);
        String sign = Sha1Util.SHA1(queryParams, key);// 计算签名
        queryParams.put("sign", sign);

        logger.info("empId:" + empId);
        logger.info("url:" + url);
        logger.info("sign:" + sign);
        String result = HttpClientUtils.doPost(url, queryParams);// 发送请求
        if (result != null) {
            result = result.replace("null", "''");
            Map<String, Object> b1Map = FastJsonUtils.stringToCollect(result);
            if (b1Map != null && b1Map.size() > 0) {
                if (b1Map.get("isSuc") != null && (b1Map.get("isSuc").equals("y"))) {
                    //接口成功掉用后处理

                }
            }

        }



    }










}
